package com.android.lovepick.other;

import java.lang.ref.WeakReference;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;

import com.android.lovepick.ChatListActivity;
import com.android.lovepick.http.HttpHelper;
import com.android.lovepick.util.Constant;

public class GetNewMsgService extends Service
{
	private final String TAG = "GetNewMsgService";
	private boolean isRunning = false;
	private GetNewMsgHandler mHandler = null;
	private int mLastID = 0;

	@Override
	public void onCreate()
	{
		mHandler = new GetNewMsgHandler(this);
		Log.i(TAG, "service create");
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId)
	{
		Log.i(TAG, "service start");
		this.isRunning = true;
		mLastID = intent.getIntExtra("last_id", 0);

		while (isRunning)
		{
			Log.i(TAG, "===http request start===");
			Thread thread = new Thread(new Runnable()
			{

				public void run()
				{
					// TODO Auto-generated method stub
					getMsg();
				}
			});
			thread.start();
			try
			{
				Thread.sleep(10000);
			}
			catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		stopSelf(startId);
		Log.i(TAG, "service stop");
		return START_NOT_STICKY;
	}

	@Override
	public IBinder onBind(Intent arg0)
	{
		// TODO Auto-generated method stub
		return null;
	}

	private void getMsg()
	{
		Log.i(TAG, "get new msgs");
		String url = Constant.HTTP_GET_NEW_MSG_URL;
		String _r = String.valueOf(Math.random());
		url += "&_r=" + _r;
		url += "&LastID=" + String.valueOf(mLastID);
		HttpHelper httpHelper = new HttpHelper();
		String msg = httpHelper.doGet(url);
		Message message = new Message();
		message.obj = (String) msg;
		message.what = Constant.MSG_HTTP_SUCCESS;
		mHandler.sendMessage(message);
	}

	/**
	 * 获取服务运行状态
	 * 
	 * @return the isRunning
	 *         <ul>
	 *         <li>true: 服务正在运行</li>
	 *         <li>false: 服务已停止</li>
	 *         </ul>
	 */
	public boolean isRunning()
	{
		return isRunning;
	}

	/**
	 * 设置服务的状态
	 * 
	 * @param isRunning
	 *            <ul>
	 *            <li>true: 服务运行</li>
	 *            <li>false: 停止服务</li>
	 *            </ul>
	 */
	public void setRunning(boolean isRunning)
	{
		this.isRunning = isRunning;
	}

	private static class GetNewMsgHandler extends Handler
	{
		private WeakReference<GetNewMsgService> mReference;
		private GetNewMsgService mService;

		public GetNewMsgHandler(GetNewMsgService service)
		{
			mReference = new WeakReference<GetNewMsgService>(service);
			mService = mReference.get();
		}

		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
				case Constant.MSG_HTTP_SUCCESS:
					String result = (String) msg.obj;
					if (!result.equals("error"))
					{
						try
						{
							JSONObject jsonObject = new JSONObject(result);
							mService.mLastID = jsonObject.getInt("last_id");
							String messages = jsonObject.getJSONArray(
									"messages").toString();
							notifyNewMsg(messages);
						}
						catch (JSONException e)
						{
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					break;

				default:
					break;
			}
		}

		private void notifyNewMsg(String newMsg)
		{
			NotificationCompat.Builder builder = new NotificationCompat.Builder(
					mService).setContentTitle("有新的消息, 点击查看.").setContentText(
					"新消息提示!");
			// Creates an explicit intent for an Activity in your app
			Intent resultIntent = new Intent(mService, ChatListActivity.class);
			resultIntent.putExtra("messages", newMsg);

			TaskStackBuilder stackBuilder = TaskStackBuilder.create(mService);
			stackBuilder.addParentStack(ChatListActivity.class);
			stackBuilder.addNextIntent(resultIntent);
			PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
					0, PendingIntent.FLAG_UPDATE_CURRENT);

			builder.setContentIntent(resultPendingIntent);
			NotificationManager mNotificationManager = (NotificationManager) mService
					.getSystemService(Context.NOTIFICATION_SERVICE);
			// mId allows you to update the notification later on.
			mNotificationManager.notify(0, builder.getNotification());
		}
	}

}
